/*************************************************************************
** Copyright (C) 2014  Mario Marquez <maqzma@gmail.com>.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/

#include "Time.h"

#include "Timer.h"

#include <iostream>

using std::cerr;
using std::endl;

Time::Time(const Tick &tick)
    : _seconds(0), _minutes(0), _hours(0), _tick(tick)
{
    _timer = new Timer(std::bind(&Time::_ptick, this),
                       Timer::Interval(1000), false);
}

Time::~Time()
{
    _timer->stop();
    delete _timer;
}

void Time::start()
{
    _timer->start();
}

void Time::pause()
{
    _timer->stop();
}

void Time::restart()
{
    _timer->stop();

    _seconds = 0;
    _minutes = 0;
    _hours = 0;
}

bool Time::counting()
{
    return _timer->running();
}

unsigned int Time::seconds() const
{
    return _seconds;
}

unsigned int Time::minutes() const
{
    return _minutes;
}

unsigned int Time::hours() const
{
    return _hours;
}

void Time::setTick(const Time::Tick &tick)
{
    if (_timer->running() == false)
        _tick = tick;
    else
        cerr << "Can not change Tick property: "
             << "The timer is running!" << endl;
}

const Time::Tick &Time::tick()
{
    return _tick;
}

void Time::_ptick()
{
    _seconds++;

    if (_seconds >= 60) {
        _seconds = 0;
        _minutes++;
    }

    if (_minutes >= 60) {
        _minutes = 0;
        _hours++;
    }

    if (this->tick() != nullptr)
        this->tick()();
    else
        cerr << "Can not call Tick: "
                << "Tick is nullptr!" << endl;
}
